#引入依赖模块
uuid      =   require 'node-uuid'
utf8      =   require 'utf8'
crypto    =   require 'crypto'
request   =   require 'request'

#-----------------------------Access Key ID 和 Access Key Secret---------------------#
access_key_id                           =           'v99w5K1D0TLXjMDr'
access_key_secret                       =           'q085Jj8PcUoM1a83t3GPJmH5Suj4jm'

#--------------------------------公共请求参数-----------------------------------------#
parameters=[]
parameters['Format']                    =           'JSON'
parameters['Version']                   =           '2014-05-26'
parameters['AccessKeyId']               =            access_key_id
parameters['SignatureMethod']           =           'HMAC-SHA1'
parameters['TimeStamp']                 =            new Date().toISOString()
parameters['SignatureVersion']          =           '1.0'
parameters['SignatureNonce']            =            uuid.v4()


#-------------------------------------------------------------------------------------
#阿里云接口类
class aliyunApi
  constructor:(@config)->

  #查询实例列表
  getInstances:(cb)->

    #私有请求参数
#    parameters['Action']              =             'DescribeInstances'
#    parameters['RegionId']            =             'cn-beijing'

    #重新生成TimeStamp和SignatureNounce
    parameters['TimeStamp'] = new Date().toISOString()
    parameters['SignatureNonce'] = uuid.v4()

    #读取传入参数
    parameters["#{key}"]=value for key,value of @config

    exports._sendResult parameters,access_key_secret,cb

  setConfig:(config)->
    @config=config
    @

#请求Url生成
exports._getRequestUrl=(parameters,access_key)->
  arr_key=[]
  arr_sort=[]
  query_string=''

  for key,value of parameters
    arr_key.push key

  arr_key.sort()

  for key,value of arr_key
    key_sort=encodeURIComponent(value)
    arr_sort[key_sort]=encodeURIComponent parameters[value]


  for key,value of arr_sort
    query_string += (key + '='+value+'&')

  query_string= query_string.slice 0,query_string.length-1

  stringTOSign= 'GET&%2F&'+encodeURIComponent query_string

  hema=crypto.createHmac 'sha1',access_key+'&'
  hema.update(stringTOSign)
  signature=hema.digest()
  signature=signature.toString('base64')

  request_url="http://ecs.aliyuncs.com/?"+"signature="+encodeURIComponent(signature)+"&"+query_string

  return request_url

#返回数据
exports._sendResult=(parameters,access_key_secret,cb)->
  request_url=exports._getRequestUrl parameters,access_key_secret    #获取请求Url

  request request_url,(error,response,body)->
    if not error and (response.statusCode is 200)
      cb body
    else
      cb '{"error":"error"}'
module.exports=aliyunApi
